/*
 * Copyright 2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

export interface ScheduleJob {
  id: number
  jobName: string
  jobGroup: string
  jobClass: string
  cronExpression: string
  jobData?: string
  description?: string
  status: 'ACTIVE' | 'PAUSED' | 'DELETED'
  createTime?: string
  updateTime?: string
}

export class SchedulerApiService {
  private static readonly BASE_URL = '/api/scheduler'

  static async getAllJobs(): Promise<ScheduleJob[]> {
    const res = await fetch(`${this.BASE_URL}/jobs`)
    if (!res.ok) throw new Error('获取任务列表失败')
    return await res.json()
  }

  static async getJob(id: number): Promise<ScheduleJob> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}`)
    if (!res.ok) throw new Error('获取任务详情失败')
    return await res.json()
  }

  static async addJob(job: Partial<ScheduleJob>): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(job)
    })
    if (!res.ok) throw new Error('添加任务失败')
    return await res.json()
  }

  static async updateJob(id: number, job: Partial<ScheduleJob>): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(job)
    })
    if (!res.ok) throw new Error('更新任务失败')
    return await res.json()
  }

  static async deleteJob(id: number): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}`, { method: 'DELETE' })
    if (!res.ok) throw new Error('删除任务失败')
    return await res.json()
  }

  static async pauseJob(id: number): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}/pause`, { method: 'POST' })
    if (!res.ok) throw new Error('暂停任务失败')
    return await res.json()
  }

  static async resumeJob(id: number): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}/resume`, { method: 'POST' })
    if (!res.ok) throw new Error('恢复任务失败')
    return await res.json()
  }

  static async runJobNow(id: number): Promise<any> {
    const res = await fetch(`${this.BASE_URL}/jobs/${id}/run`, { method: 'POST' })
    if (!res.ok) throw new Error('立即执行任务失败')
    return await res.json()
  }
} 